package com.taotao.taodada.scoring;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.taotao.taodada.manager.GMLAiManager;
import com.taotao.taodada.manager.QWAiManager;
import com.taotao.taodada.model.dto.question.QuestionAnswerDTO;
import com.taotao.taodada.model.dto.question.QuestionContentDTO;
import com.taotao.taodada.model.entity.App;
import com.taotao.taodada.model.entity.Question;
import com.taotao.taodada.model.entity.UserAnswer;
import com.taotao.taodada.model.vo.QuestionVO;
import com.taotao.taodada.service.QuestionService;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author： HTTT
 * @Date： 2024/6/13 15:03
 * @Describe：
 */
@ScoringStrategyConfig(appType = 1, scoringStrategy = 1)
public class AiTestScoringStrategy implements ScoringStrategy{
    @Resource
    private QuestionService questionService;

    @Resource
    private GMLAiManager GMLAiManager;
    @Resource
    private QWAiManager qwAiManager;
    @Value("${ai}")
    private String ai;

    private final Cache<String,String> answerCacheMap = Caffeine.newBuilder().initialCapacity(1024)
            .expireAfterAccess(5L, TimeUnit.MINUTES)
            .build();
    private static final String AI_TEST_SCORING_SYSTEM_MESSAGE = "你是一位严谨的判题专家，我会给你如下信息：\n" +
            "```\n" +
            "应用名称，\n" +
            "【【【应用描述】】】，\n" +
            "题目和用户回答的列表：格式为 [{\"title\": \"题目\",\"answer\": \"用户回答\"}]\n" +
            "```\n" +
            "\n" +
            "请你根据上述信息，按照以下步骤来对用户进行评价：\n" +
            "1. 要求：需要给出一个明确的评价结果，包括评价名称（尽量简短）和评价描述（尽量详细，大于 200 字）\n" +
            "2. 严格按照下面的 json 格式输出评价名称和评价描述\n" +
            "```\n" +
            "{\"resultName\": \"评价名称\", \"resultDesc\": \"评价描述\"}\n" +
            "```\n" +
            "3. 返回格式必须为 JSON 对象";

    /**
     * AI 评分策略
     * @param choices
     * @param app
     * @return
     * @throws Exception
     */
    @Override
    public UserAnswer doScore(List<String> choices, App app) throws Exception {
        Long appId = app.getId();
        String choicesStr = JSONUtil.toJsonStr(choices);
        //1.根据id查询到题目
        Question question = questionService.getOne(
                Wrappers.lambdaQuery(Question.class).eq(Question::getAppId,appId)
        );
        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContentDTO> questionContent = questionVO.getQuestionContent();
        //构建key
        String cacheKey = buildCacheKey(appId, choicesStr, question.getUpdateTime().toString());
        //先查询缓存中有没有
        String json;
        json = answerCacheMap.getIfPresent(cacheKey);
        if(StringUtils.isBlank(json)){
            // 2. 调用 AI 获取结果
            // 封装 Prompt
            String userMessage = getAiTestScoringUserMessage(app, questionContent, choices);
            // AI 生成
            String result;
            if("gml".equals(ai)){
                result = GMLAiManager.doStableRequest(AI_TEST_SCORING_SYSTEM_MESSAGE, userMessage);
            }else{
                result = qwAiManager.doRequest(AI_TEST_SCORING_SYSTEM_MESSAGE, userMessage);
            }
            System.out.println(result);
            // 截取需要的 JSON 信息
            int start = result.indexOf("{");
            int end = result.lastIndexOf("}");
            json = result.substring(start, end + 1);
        }
        // 3. 构造返回值，填充答案对象的属性
        answerCacheMap.put(cacheKey,json);
        UserAnswer userAnswer = JSONUtil.toBean(json, UserAnswer.class);
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        return userAnswer;
    }

    /**
     * AI 评分用户消息封装
     *
     * @param app
     * @param questionContentDTOList
     * @param choices
     * @return
     */
    private String getAiTestScoringUserMessage(App app, List<QuestionContentDTO> questionContentDTOList, List<String> choices) {
        StringBuilder userMessage = new StringBuilder();
        userMessage.append(app.getAppName()).append("，\n");
        userMessage.append("【【【").append(app.getAppDesc()).append("】】】，").append("\n");
        List<QuestionAnswerDTO> questionAnswerDTOList = new ArrayList<>();
        for (int i = 0; i < questionContentDTOList.size(); i++) {
            QuestionAnswerDTO questionAnswerDTO = new QuestionAnswerDTO();
            questionAnswerDTO.setTitle(questionContentDTOList.get(i).getTitle());
            questionAnswerDTO.setUserAnswer(choices.get(i));
            questionAnswerDTOList.add(questionAnswerDTO);
        }
        userMessage.append(JSONUtil.toJsonStr(questionAnswerDTOList));
        return userMessage.toString();
    }
    private String buildCacheKey(Long appId,String choice,String time){
        return DigestUtil.md5Hex(appId+":"+choice+":"+time);
    }
}
